import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/LoginView.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/auth/RegisterView.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/layouts/DashboardLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        redirect: '/student'
      },
      {
        path: 'student',
        component: () => import('@/views/student/DashboardView.vue'),
        meta: { role:'student' },
        children: [
          {
            path: '',
            name: 'StudentHome',
            component: () => import('@/views/student/HomeView.vue')
          },
          {
            path: 'exams',
            name: 'StudentExamList',
            component: () => import('@/views/student/ExamListView.vue')
          },
          {
            path: 'exam/:id',
            name: 'StudentExam',
            component: () => import('@/views/student/ExamView.vue')
          },
          {
            path: 'results',
            name: 'StudentGradeList',
            component: () => import('@/views/student/GradeListView.vue')
          },
          {
            path: 'results/:id',
            name: 'StudentGradeDetail',
            component: () => import('@/views/student/ResultView.vue')
          },
          {
            path: 'grade-appeal',
            name: 'StudentGradeAppeal',
            component: () => import('@/views/student/GradeAppealView.vue')
          },
          {
            path: 'profile',
            name: 'StudentProfile',
            component: () => import('@/views/common/ProfileView.vue')
          }
        ]
      },
      {
        path: 'teacher',
        component: () => import('@/views/teacher/DashboardView.vue'),
        meta: { role: 'teacher' },
        children: [
          {
            path: '',
            name: 'TeacherHome',
            component: () => import('@/views/teacher/HomeView.vue')
          },
          {
            path: 'questions',
            name: 'TeacherQuestionManage',
            component: () => import('@/views/teacher/QuestionManageView.vue')
          },
          {
            path: 'questions/category',
            name: 'TeacherQuestionCategory',
            component: () => import('@/views/teacher/QuestionCategoryView.vue')
          },
          {
            path: 'exams',
            name: 'TeacherExamList',
            component: () => import('@/views/teacher/ExamListView.vue')
          },
          {
            path: 'exams/create',
            name: 'TeacherExamCreate',
            component: () => import('@/views/teacher/ExamEditView.vue')
          },
          {
            path: 'exams/edit/:id',
            name: 'TeacherExamEdit',
            component: () => import('@/views/teacher/ExamEditView.vue')
          },
          {
            path: 'monitor/:id',
            name: 'TeacherExamMonitor',
            component: () => import('@/views/teacher/ExamMonitorView.vue')
          },
          {
            path: 'results/:id',
            name: 'TeacherGradeList',
            component: () => import('@/views/teacher/GradeStatisticsView.vue')
          },
          {
            path: 'grade/:examId/:studentId',
            name: 'TeacherGrading',
            component: () => import('@/views/teacher/PaperGradingView.vue')
          },
          {
            path: 'templates',
            name: 'TeacherExamTemplate',
            component: () => import('@/views/teacher/ExamTemplateView.vue')
          },
          {
            path: 'profile',
            name: 'TeacherProfile',
            component: () => import('@/views/common/ProfileView.vue')
          },
          {
            path: 'auto-grading',
            name: 'TeacherAutoGrading',
            component: () => import('@/views/teacher/AutoGradingView.vue')
          },
          {
            path: 'grade-analysis',
            name: 'TeacherGradeAnalysis',
            component: () => import('@/views/teacher/GradeAnalysisView.vue')
          }
        ]
      },
      {
        path: 'admin',
        component: () => import('@/views/admin/DashboardView.vue'),
        meta: { role: 'admin' },
        children: [
          {
            path: '',
            name: 'AdminHome',
            component: () => import('@/views/admin/HomeView.vue')
          },
          {
            path: 'users',
            name: 'AdminUserManage',
            component: () => import('@/views/admin/UserManageView.vue')
          },
          {
            path: 'system',
            name: 'AdminSystemSettings',
            component: () => import('@/views/admin/SystemSettingsView.vue')
          },
          {
            path: 'notifications',
            name: 'AdminNotification',
            component: () => import('@/views/admin/NotificationManageView.vue')
          },
          {
            path: 'backup',
            name: 'AdminBackup',
            component: () => import('@/views/admin/BackupManageView.vue')
          },
          {
            path: 'logs',
            name: 'AdminLogs',
            component: () => import('@/views/admin/SystemLogsView.vue')
          },
          {
            path: 'profile',
            name: 'AdminProfile',
            component: () => import('@/views/common/ProfileView.vue')
          }
        ]
      }
    ]
  }
]

// 标记是否显示过未登录提示
let hasShownLoginMessage = false

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  // 定义白名单路径
  const whiteList = ['/login', '/register']
  const isWhitePage = whiteList.includes(to.path)
  
  // 重置登录消息标记（当导航到登录页时）
  if (to.path === '/login') {
    hasShownLoginMessage = false
  }
  
  // 如果是白名单页面
  if (isWhitePage) {
    if (authStore.isAuthenticated) {
      // 已登录状态下访问登录页，重定向到对应角色首页
      if (to.path === '/login') {
        next({ path: `/${authStore.userRole}` })
        return
      }
    }
    // 未登录访问白名单页面，直接通过
    next()
    return
  }
  
  // 非白名单页面，检查登录状态
  try {
    // 验证登录状态
    await authStore.islogin()
    
    // 确保有用户信息
    if (!authStore.user) {
      await authStore.loadUserInfo()
    }
    
    // 检查路由角色权限
    if (to.meta.role) {
      const allowedRoles = Array.isArray(to.meta.role) ? to.meta.role : [to.meta.role]
      if (!allowedRoles.includes(authStore.userRole)) {
        ElMessage.error('无权访问该页面')
        next({ path: `/${authStore.userRole}` })
        return
      }
    }
    
    hasShownLoginMessage = false
    next()
    
  } catch (error) {
    authStore.removeToken()
    
    // 只在第一次未登录时显示提示
    if (!hasShownLoginMessage) {
      // 区分是首次访问还是token失效
      if (from.path === '/login' || from.path === '') {
        ElMessage.warning('请先登录')
      }
      hasShownLoginMessage = true
    }
    
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
  }
})

export default router 

// // 路由守卫
// router.beforeEach(async (to, from, next) => {
//   const authStore = useAuthStore()
  
//   // 如果目标路由不是登录页
//   if (to.path !== '/login') {
//     try {
//       await authStore.islogin()
//       // islogin 方法中已经处理了未登录的情况（会自动跳转到登录页）
//       next()
//     } catch (error) {
//       next({ path: '/login' })
//     }
//   } else {
//     next()
//   }

//   // 白名单路径
//   const whiteList = ['/login', '/register']
  
//   if (authStore.isAuthenticated) {
//     // 已登录状态下访问登录页，重定向到首页
//     if (to.path === '/login') {
//       // next({ path: '/' })
//       next({ path: `/${authStore.userRole}` })
//     } else {
//       // 如果没有用户信息，先获取用户信息
//       if (!authStore.user) {
//         try {
//           await authStore.loadUserInfo()
//         } catch (error) {
//           authStore.logout()
//           next('/login')
//           return
//         }
//       }

//       // 检查路由是否需要特定角色权限
//       if (to.meta.role) {
//         const allowedRoles = Array.isArray(to.meta.role) ? to.meta.role : [to.meta.role]
//         if (!allowedRoles.includes(authStore.userRole)) {
//           ElMessage.error('无权访问该页面')
//           next({ path: '/' })
//           return
//         }
//       }
//       next()
//     }
//   } else {
//     if (whiteList.includes(to.path)) {
//       next()
//     } else {
//       // ElMessage.warning('请先登录')
//       next({ path: '/login', query: { redirect: to.fullPath } })
//     }
//   }
// })

// export default router 